package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"ware-sys/chone"
	"ware-sys/modler"
)

func UserList(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	video := modler.Video{

		Title:   title,
		Content: content,
		Author:  author,
	}
	err := modler.DB.Create(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "UserList" + strconv.Itoa(int(video.ID))
	var list modler.Video
	modler.DB.Where("id=?", video.ID).First(&list)
	marshal, _ := json.Marshal(&list)
	chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserDel(c *gin.Context) {
	id := c.Query("id")
	var video []modler.Video
	err := modler.DB.Where("id=?", id).First(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": video,
		})
		return
	}
}

func Del(c *gin.Context) {
	id := c.Query("id")

	err := modler.DB.Where("id=?", id).Delete(&modler.Video{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "del" + id
	chone.Rdb.Get(chone.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func List(c *gin.Context) {
	var video []modler.Video
	redis_key := "list"
	er, _ := chone.Rdb.Get(chone.Ctx, redis_key).Result()
	if er == "" {
		modler.DB.Find(&video)
		marshal, _ := json.Marshal(&video)
		chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(er), &video)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": video,
	})
	return
}
